var express		= require('express');
var app = require('express')(),
	server = require('http').createServer(app);
var fs			= require("fs");
var bodyParse	= require('body-parser');
var path		= require('path');
var url			= require("url");
var querystring	= require("querystring");
var formidable = require('formidable');
var tiMsg = require('./routes/TiMsg');

// http://192.168.1.116:3000/?userid=000001&type=1
// http://192.168.1.116:3000/?kfid=1234567&type=1
// http://192.168.1.116:3000/?kfid=1234567&type=2
// http://192.168.1.116:3000/?kfid=1234567&type=3
// http://192.168.1.116:3000/
// http://192.168.1.116:3000/?token=9d3f09572a9edf7784a825378afdd888&service_type=1

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port: 8080});
// 连接池
// req:用于获得客户端（浏览器）的信息
// res:用于向客户端（浏览器）返回信息
// var clients = {};
var clientsYH = {};	// 用户连接池
var clientsKF = {}; // 客服连接池
var clientsGH = {}; // 公会客服连接池
var clientsCG = {}; // 超管客服连接池
var clientsKFArr = [];
var clientsGHArr = [];
var clientsCGArr = [];
wss.on('connection', function(ws) {
	// 收到连接信息
    ws.on('message', function(message) {
		message = JSON.parse(message);
		if (message.type === "REGISTER_KF") {
			clientsKF[message.kfid] = ws;
			clientsKFArr.push(message.kfid);
			console.log("普通客服链接");
		}else if (message.type === "REGISTER_GH") {
			clientsGH[message.kfid] = ws;
			clientsGHArr.push(message.kfid);
			console.log("公会客服链接");
		}else if (message.type === "REGISTER_CG") {
			clientsCG[message.kfid] = ws;
			clientsCGArr.push(message.kfid);
			console.log("超管客服链接");
		}else if (message.type === "REGISTER_YH") {
			console.log("用户链接");
			clientsYH[message.userid] = ws;
		}else if (message.type === 'CHATMSG_KF') {
			tiMsg.w_write_chat_record(message.data.mineID,message.data.targetID,message.data.mineCONTENT);
			clientsKF[message.data.targetID].send(JSON.stringify({type:'CHATMSG_KF',data:message}));
       	}else if (message.type === 'CHATMSG_GH') {
			clientsGH[message.data.targetID].send(JSON.stringify({type:'CHATMSG_GH',data:message}));
			tiMsg.w_write_chat_record(message.data.mineID,message.data.targetID,message.data.mineCONTENT);
		}else if (message.type === 'CHATMSG_CG') {
			clientsCG[message.data.targetID].send(JSON.stringify({type:'CHATMSG_CG',data:message}));
			tiMsg.w_write_chat_record(message.data.mineID,message.data.targetID,message.data.mineCONTENT);
		}else if (message.type === 'CHATMSG_YH') {
			clientsYH[message.data.targetID].send(JSON.stringify({type:'CHATMSG_YH',data:message}));
			tiMsg.w_write_chat_record(message.data.mineID,message.data.targetID,message.data.mineCONTENT);
		}
    });

    // ws.on('close', function(message) {
    //     // 连接关闭时，将其移出连接池
    //     clients = clients.filter(function(ws1){
    //         return ws1 !== ws
    //     })
    // });
});

app.use(bodyParse.urlencoded({extended:true}));
// 通过这句话，可以将一个工具类的js脚本放到public文件夹中 
app.use(express.static(path.join(__dirname, 'public')));


// 处理get请求
app.get('/',async(req,res)=>{
	//获取返回的url对象的query属性值 
	var arg = url.parse(req.url).query;
	if(arg) {
		//将arg参数字符串反序列化为一个对象
		var params = querystring.parse(arg);
		console.log("params = ",params);
		// 请求的方式
		console.log("method = " + req.method);
		// 请求的url
		console.log("url = " + req.url);

		// if(!params.type) {
		if(params.kfid && params.type) {	
			// 设置上半段脚本定义的内容 包括用户id和 对应客服id
			var str = "<div><script>var kfid=" + params.kfid + "\n var type=" + params.type + "</script></div>";
			fs.readFile("public/computer.html",function(err,data){
				// body
				if(err){
					console.log(err);
					//404：NOT FOUND
					res.writeHead(404,{"Content-Type":"text/html"});
				}
				else{
					//200：OK
					res.writeHead(200,{"Content-Type":"text/html"});		// 包头
					res.write(str + data.toString());						// 结合甩出上半段脚本和下半段html页面
				}
				res.end();
			});
			console.log('客服打开+++++++++++++++++++',params.kfid,params.type);
		}else if(params.token && params.service_type){			
			// 设置上半段脚本定义的内容 包括用户id和 对应客服id
			if(params.service_type == 1) {
				var onlineKF = Math.floor(Math.random() * clientsKFArr.length);
				var kfid = clientsKFArr[onlineKF];
			}else if(params.service_type == 2) {
				var kfid = clientsGHArr[0];
			}else if(params.service_type == 3) {
				var kfid = clientsCGArr[0];
			}
			var user_data = await tiMsg.w_user_login(params.token);
			if(user_data.length >= 1) {
				console.log(user_data[0][0].uid,user_data[0][0].nickname,user_data[0][0].avatar,"用户上传token后返回什么?");
				var str = "<div><script>var userid=" + user_data[0][0].uid
						+ "\n var username='" + user_data[0][0].nickname 
						+ "'\n var avatar='" + user_data[0][0].avatar
						+ "'\n var kfid=" + kfid
						+ "\n var YWtype=" + params.service_type + "</script></div>";
				fs.readFile("public/mobile.html",function(err,data){
					// body
					if(err){
						console.log(err);
						//404：NOT FOUND
						res.writeHead(404,{"Content-Type":"text/html"});
					}
					else{
						//200：OK
						res.writeHead(200,{"Content-Type":"text/html"});		// 包头
						res.write(str + data.toString());						// 结合甩出上半段脚本和下半段html页面
					}
					res.end();
				});
			}
			console.log('用户打开+++++++++++++++++++');
		}
	}else {
		res.sendfile('./public/login.html');
	}
})
// 客服登陆时触发
app.post('/login', async (req,res) => {
	console.log(req.body.id,req.body.password,'login出去');
	let kf_data = await tiMsg.w_service_login(req.body.id,req.body.password);
	if(kf_data.length >= 1) {
		console.log(kf_data[0][0].error,'login进来了然后？');
		if(kf_data[0][0].error == 0) {
			// res.json({"status":"success",id:req.body.id,type:rows[0].type});
			res.json({"status":"success",id:req.body.id,type:kf_data[0][0].type});
			console.log('登陆成功');
		}else if(kf_data[0][0].error == 1) {
			res.json({"status":"fail","msg":'用户名或密码错误，登陆失败'});
			console.log('客服id不存在');
		}else if(kf_data[0][0].error == 2) {
			res.json({"status":"fail","msg":'用户名或密码错误，登陆失败'});
			console.log('密码错误');
		}
	}else {
		res.json({"status":"fail","msg":'内部错误，请稍后重试。'});
		console.log('内部错误，请稍后重试。');
	}
});
app.post("/upload/image",function (req,res) {
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.uploadDir = path.join(__dirname + "/public/upload/");
    form.keepExtensions = true;//保留后缀
    form.maxFieldsSize = 2 * 1024 * 1024;
    //处理图片
    form.parse(req, function (err, fields, files){
        var filename = files.file.name;
        var nameArray = filename.split('.');
        var type = nameArray[nameArray.length - 1];
        var name = '';
        for (var i = 0; i < nameArray.length - 1; i++) {
            name = name + nameArray[i];
        }
        var date = new Date();
        var time = '_' + date.getFullYear() + "_" + date.getMonth() + "_" + date.getDay() + "_" + date.getHours() + "_" + date.getMinutes();
        var avatarName = name + time + '.' + type;
		var newPath = form.uploadDir + avatarName;
        fs.renameSync(files.file.path, newPath);  //重命名
		res.json({
			"code": 0,						//0表示成功，其它表示失败
			"msg": "", 						//失败信息
			"data": {
			  "src": "/upload/"+avatarName, //图片url
			}
		})
    })
});
server.listen(3000);
